{-# LANGUAGE OverloadedStrings               #-}
{-# LANGUAGE QuasiQuotes,ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell              #-}
module CMS.Handler.Home
  ( getHomeR
  , getArticleR
  , getArticleCateListR
  , getArticleHomeR
  )
where
import           CMS.Data
import           Yesod
import           CMS.View.Home
import           CMS.View.Common
import qualified App.UserCenter.Core           as UC
import           App.Article.DB
import           App.Article.Manager
import           Data.Int
import           CMS.View.Article
import           Control.Monad
import           Data.Either
import           App.Common.Table
import Data.Text
import qualified Data.Map as M
getHomeR :: Handler Html
getHomeR = do
  loginUser <- UC.getLoginUser
  mayUserID <- UC.getLoginUserId
  newsList  <- getNewsArticle mayUserID 11
  tailCA    <- getTailCateAndArticle mayUserID 10
  Master _ _ mayTpl <- getYesod
  let retMap::M.Map String Value = M.fromList [("news",toJSON newsList)]
  case mayTpl of
    Nothing -> indexLayout (wHome loginUser newsList tailCA) loginUser
    Just _  ->  renderTpl "index.html" (toJSON retMap)

getArticleR :: Int64 -> Handler Html
getArticleR aid = do
  loginUser <- UC.getLoginUser
  mayUserID <- UC.getLoginUserId
  mArticle  <- getArticle mayUserID aid
  newsList  <- getNewsArticle mayUserID 20
  case mArticle of
    Left  l         -> jumpMessage l HomeR loginUser
    Right r@(id, a) -> indexLayout (wArticle loginUser r newsList) loginUser

getArticleCateListR :: Int64 -> Handler Html
getArticleCateListR cid = do
  loginUser <- UC.getLoginUser
  mayUserID <- UC.getLoginUserId
  eCate     <- getCateInfo cid
  case eCate of
    Left  l -> jumpMessage l HomeR loginUser
    Right r -> do
      articleLst <-
        queryArticle mayUserID
                     [ArticleOwnerCateId ==. cid]
                     [Desc ArticleCreateTime]
          $ PageInfo 0 50
      indexLayout (wArticleCateList loginUser r $ tableData articleLst)
                  loginUser

getArticleHomeR :: Handler Html
getArticleHomeR = do
  loginUser <- UC.getLoginUserAndId
  cateLst   <- queryCate (-1)
  indexLayout (wArticleHome loginUser cateLst) (snd <$> loginUser)
